FabricJS 如何把多段线对象序列化为JSON 您所在的位置:网站首页 js json处理 FabricJS 如何把多段线对象序列化为JSON

FabricJS 如何把多段线对象序列化为JSON

2023-02-22 09:21| 来源: 网络整理| 查看: 265

FabricJS 如何把多段线对象序列化为JSON

多段线对象可以由一组相连的直线段来描述。由于它是FabricJS的基本元素之一,我们也可以通过应用角度、不透明度等属性来轻松定制它。

序列化是指将画布转换为可保存的数据,以后可将其转换回画布中。这种数据可以是一个对象或JSON,这样它就可以存储在服务器上。我们将使用 toJSON() 方法将带有Polyline对象的画布转换成JSON。

语法 toJSON(propertiesToInclude: Array): Object 参数 propertiesToInclude – 这个参数接受一个 数组 ,其中包含我们可能想要在输出中额外包括的任何属性。这个参数是可选的。 示例1:使用toJSON方法

让我们看一个代码例子,看看使用 toJSON 方法时的日志输出。在这种情况下,Polyline实例的JSON表示将被返回。

Using the toJSON method

You can open console from dev tools and see that the logged output contains the JSON representation of the Polyline instance

// Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiate a Polyline instance var polyLine = new fabric.Polyline([ { x: 500, y: 20 }, { x: 550, y: 60 }, { x: 550, y: 200 }, { x: 350, y: 100 }, { x: 350, y: 60 }, ], { stroke: "orange", fill: "white", strokeWidth: 5, }); // Add it to the canvas canvas.add(polyLine); // Using the toJSON method console.log("JSON representation of the Polyline instance is: ", polyLine.toJSON()); 例2:使用toJSON方法添加额外的属性

让我们看一个代码例子,看看我们如何通过使用 toJSON 方法来包含额外的属性。在这个例子中,我们添加了一个名为 “name “的自定义属性。我们可以将特定的属性传递给 fabric.Polyline 实例作为options对象的第二个参数,并将相同的键传递给 toJSON 方法。

Using toJSON method to add additional properties

You can open console from dev tools and see that the logged output contains JSON with the added property called name

// Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiate a Polyline object with name key // passed in options object var polyLine = new fabric.Polyline([ { x: 500, y: 20 }, { x: 550, y: 60 }, { x: 550, y: 200 }, { x: 350, y: 100 }, { x: 350, y: 60 }, ], { stroke: "orange", fill: "white", strokeWidth: 5, name: "Polyline instance", }); // Add it to the canvas canvas.add(polyLine); // Using the toJSON method console.log( "JSON representation of the Polyline instance is: ", polyLine.toJSON(["name"]) );


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有